
export default function createStore ( reducer, initState ) {

  let state = initState;

  // 收集器
  const listeners = [];

  // 获取状态
  const getState = () => {
    return state
  }

  /**
   * 
   * @param {*} listener 订阅的函数
   * @returns 取消订阅的函数
   */
  const subscribe = ( listener ) => {
    listeners.push( listener )
    return () => {
      const index = listeners.indexOf( listener )
      listeners.splice( index, 1 )
    }
  }

  /**
   * 
   * @param {*} action action提交计算新的状态
   */
  const dispatch = ( action ) => {
    state = reducer( state, action )
    listeners.forEach( listener => listener() )
  }

  dispatch( { type: '@@REDUX/INIT' } );

  return {
    getState,
    subscribe,
    dispatch
  }
}